// 使用HTTP取回文件，并操作HTTP请求头与返回头
#include <stdio.h>
#include <wchar.h>
#include <windows.h>
#include <wininet.h>

#define HOSTURL                                                             \
  "https://raw.githubusercontent.com/googlehosts/hosts/master/hosts-files/" \
  "hosts"

DWORD HttpHeaderNum(HINTERNET hReq, DWORD type) {
  DWORD num = 0;
  DWORD numlen = 4;
  HttpQueryInfoA(hReq, type | HTTP_QUERY_FLAG_NUMBER, &num, &numlen, NULL);
  return num;
}

char* HttpHeaderStr(HINTERNET hReq, DWORD type) {
  char* str = malloc(100);
  DWORD strlen = 100;
  HttpQueryInfoA(hReq, type, str, &strlen, NULL);
  return str;
}

char* HttpReadAll(HINTERNET hReq, DWORD contlen) {
  char* cont = malloc(contlen + 1);
  DWORD _;
  InternetReadFile(hReq, cont, contlen, &_);
  cont[contlen] = '\0';
  return cont;
}

void SaveTextFile(wchar_t* fname, char* data) {
  HANDLE hOut = CreateFileW(fname, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL, NULL);
  DWORD n;
  WriteFile(hOut, data, strlen(data), &n, NULL);
  CloseHandle(hOut);
}

int wmain(int argc, wchar_t** argv) {
  HINTERNET hInet =
      InternetOpenW(L"inetapp", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
  char* header = "If-None-Match: \"b4d2267ee7969846c982874b83fe54906306003b\"";
  HINTERNET hReq =
      InternetOpenUrlA(hInet, HOSTURL, header, strlen(header), 0, 0);
  if (!hReq) {
    printf("internet error");
    return 0;
  }
  DWORD status = HttpHeaderNum(hReq, HTTP_QUERY_STATUS_CODE);
  DWORD contlen = HttpHeaderNum(hReq, HTTP_QUERY_CONTENT_LENGTH);
  char* etag = HttpHeaderStr(hReq, HTTP_QUERY_ETAG);
  char* res = HttpReadAll(hReq, contlen);
  printf("status:%d\n%s", status, etag);
  InternetCloseHandle(hReq);
  InternetCloseHandle(hInet);
  return 0;
}